﻿@{
    Layout = "~/Views/Shared/_FormWhite.cshtml";
}

@section header{

    <link href="@Url.Content("~/lib/Montserrat/Montserrat.css?v=" + DateTime.Now.Ticks.ToString())" rel="stylesheet" type="text/css">

    <!-- wavesurfer.js -->
    <script src='@Url.Content("~/lib/wavesurfer/wavesurfer.js")' type="text/javascript"></script>

    <!-- plugins -->
    <script src='@Url.Content("~/lib/wavesurfer/wavesurfer.timeline.js")' type="text/javascript"></script>
    <script src='@Url.Content("~/lib/wavesurfer/wavesurfer.markers.js")' type="text/javascript"></script>
    <script src='@Url.Content("~/lib/wavesurfer/wavesurfer.minimap.js")' type="text/javascript"></script>

    <link href="@Url.Content("~/lib/summernote/0.8.15/summernote.min.css")" rel="stylesheet" type="text/css">
    <script src='@Url.Content("~/lib/summernote/0.8.15/summernote.js")' type="text/javascript"></script>

    <link href="@Url.Content("~/lib/recogito-js/recogito.min.css")" rel="stylesheet" type="text/css">
    <script src='@Url.Content("~/lib/recogito-js/recogito.min.js")' type="text/javascript"></script>

}

<style>

    body {
        font-family: 'Montserrat', sans-serif;
    }

    .form-control {
        font-size: 14px;
    }

    .layui-layer-dialog .layui-layer-content {
        word-break: normal;
    }

    .r6o-editor {
        font-family: inherit;
        font-size: 14px;
        line-height: 20px;
        width: 400px;
    }

        .r6o-editor .widget {
            margin: 0;
            padding: 0 20px;
        }

        .r6o-editor .r6o-footer {
            padding: 10px 20px 15px 20px;
        }

            .r6o-editor .r6o-footer .r6o-btn {
                line-height: 1.2;
                margin-left: 10px;
                margin-right: 0;
                min-width: 85px;
            }

    .r6o-annotation {
        border: none;
    }

    .annotation-manual {
        font-style: italic;
    }

    .option-legend, .option-text {
        display: inline-block;
    }

    .option-legend {
        border-radius: 10px;
        height: 10px;
        width: 10px;
        margin-left: 5px;
        margin-right: 10px;
    }

    .popover {
        font-family: inherit;
    }

    .utterance-popover-content {
        padding: 0;
    }

        .utterance-popover-content hr {
            margin: 0;
        }

    .utterance-popover-item {
        cursor: pointer;
        padding: 7px 14px;
    }

        .utterance-popover-item:hover {
            background-color: whitesmoke;
        }

    #waveform_wrapper {
        width: 90%;
        /*border: 1px solid #ddd;*/
    }

    #waveform_loading .loaderbox {
        border: none;
        background-color: transparent;
        -webkit-border-radius: 0px;
        -moz-border-radius: 0px;
        -ms-border-radius: 0px;
        -o-border-radius: 0px;
        border-radius: 0px;
        -webkit-box-shadow: none;
        -moz-box-shadow: none;
        box-shadow: none;
    }

    /*.wavesurfer-marker span {
        font-family: 'Montserrat', sans-serif !important;*/
    /*width: 200px !important;*/
    /*overflow: visible;
        z-index: 1000;
    }*/

    .wavesurfer-marker span {
        font-family: 'Montserrat', sans-serif !important;
        font-size: 12px;
        visibility: hidden; 
         background-color: black;
        color: #fff;
        /*color: black; */
        text-align: left;
        border-radius: 6px;
        padding: 5px 10px 5px 5px; /* Position the tooltip */
        position: fixed;
        z-index: 1000;
    }

    .wavesurfer-marker:hover span {
        visibility: visible;
    }

    .call-info {
        margin-bottom: 20px;
    }

        .call-info label {
            color: black;
            font-weight: bold;
        }

        .call-info .bold {
            color: black;
            font-weight: bold;
        }

        .call-info .row {
            margin-top: 10px;
        }

    #compare_result {
        white-space: pre-line;
        max-height: 540px;
        overflow-y: scroll;
        color: black;
    }

        #compare_result .combined_recording_column {
            font-weight: bold
        }

        #compare_result .combined_recording_row {
            background-color: #f9f9f9;
        }

        #compare_result .row {
            margin-left: 0px;
            margin-right: 0px;
            margin-top: 8px;
            margin-bottom: 8px;
        }

            #compare_result .row .time {
                /*width: 50px !important;
            padding-left: 0px;*/
                padding-right: 0px;
            }

            #compare_result .row .speaker {
                /*width: 100px !important;*/
                margin-left: 10px;
                padding-left: 0px;
                padding-right: 0px;
            }

            #compare_result .row .col-sm-9 {
                padding-left: 25px;
            }

        #compare_result .col-sm-1, #compare_result .col-sm-11 {
            color: #676a6c;
        }

        #compare_result .col-edit {
            width: 20px;
            padding-left: 0px;
            padding-right: 0px;
        }

        /*#compare_result > div:nth-of-type(even) {
            background: rgb(231, 234, 236);
        }*/

        #compare_result .transcript {
            position: relative;
        }

        #compare_result .customer_row {
            background: rgb(231, 234, 236);
        }

        #compare_result .agent_row {
            background: white;
        }

        #compare_result .transcript .stripe {
            background-color: red;
            position: absolute;
            width: 6px;
            top: 0;
            left: 0;
            bottom: 0;
        }

        #compare_result .transcript .customer {
            background-color: rgb(255, 217, 102);
        }

        #compare_result .transcript .agent {
            background-color: rgb(142, 169, 219);
        }

    .transcript_container .panel-heading {
        background-color: white;
        border-bottom: 0px;
        color: #676a6c;
    }

    .transcript_container .panel-line {
        padding-left: 14px;
        padding-right: 14px;
    }

    .transcript_container hr {
        margin-top: 0px;
        margin-bottom: 0px;
    }

    .custmer-consent .similar-words {
        color: black;
    }

    .custmer-consent .text-navy {
        color: rgb(41, 196, 77);
    }

    .custmer-consent h3 {
        font-size: 42px;
    }

    .custmer-consent h3 {
        font-size: 42px;
    }

    .custmer-consent h5 {
        font-size: 14px;
    }

    .macthed_text {
        background-color: rgb(255, 102, 102);
    }

    .macthed_text_pcp {
        background-color: rgb(1, 255, 204);
    }

    .macthed_text_callrecorded {
        background-color: lawngreen;
    }

    .macthed_text_callback {
        background-color: orangered;
    }

    .macthed_text_futurecall {
        background-color: gold;
    }

    .macthed_text_appointment {
        background-color: royalblue;
    }

    .macthed_text_medicare {
        background-color: hotpink;
    }

    .macthed_text_rx {
        background-color: violet;
    }

    .macthed_text_inboundcallback {
        background-color: darkviolet;
    }

    .macthed_text_specialistinnetwork {
        background-color: lightgray;
    }

    .macthed_text_pcpcopay {
        background-color: lightblue;
    }

    .macthed_text_specialistcopay {
        background-color: tan;
    }

    .macthed_text_drugtiers {
        background-color: mediumpurple;
    }

    .macthed_text_hospitalcopay {
        background-color: slategray;
    }

    .macthed_text_premium {
        background-color: mediumvioletred;
    }

    .macthed_text_maxoutofpocket {
        background-color: steelblue;
    }

    .macthed_text_pcpcoinsurance {
        background-color: navajowhite;
    }

    .macthed_text_specialistcoinsurance {
        background-color: lightgreen;
    }

    .macthed_text_hospitalcoinsurance {
        background-color: lemonchiffon;
    }

    .macthed_keyword {
        background-color: #ffd9b0;
    }

    .macthed_entity {
        position: relative;
        display: inline-block;
    }

    .macthed_entity_person {
        border-bottom: 3px solid rgb(206, 109, 189);
    }

    .macthed_entity_date {
        border-bottom: 3px solid rgb(0, 115, 187);
    }

    .macthed_entity .tooltiptext {
        font-size: 12px;
        visibility: hidden;
        width: 120px;
        background-color: black;
        color: #fff;
        text-align: left;
        border-radius: 6px;
        padding: 5px 10px 5px 5px;
        margin-left: 10px;
        /* Position the tooltip */
        position: absolute;
        z-index: 1;
    }

    .macthed_entity:hover .tooltiptext {
        visibility: visible;
    }

    .macthed_text .macthed_keyword {
        background-color: rgb(255, 102, 102)
    }

    .note-editing-area {
        padding: 10px;
    }

    .comment-cta {
        display: none;
    }

    .comment-item {
        border-left: 5px solid transparent;
        border-bottom: 1px solid rgb(235, 235, 235);
        padding: 10px;
    }

        .comment-item:hover {
            border-left: 5px solid rgb(52,114,176);
            background-color: whitesmoke;
        }

    .comment-heading {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .comment-avatar {
        height: 16px;
    }

    .comment-avatar-lg {
        height: 32px;
    }

    .comment-author {
        margin-left: 5px;
    }

    .comment-text {
        display: none;
        margin-left: 10px;
    }

    .comment-body {
        margin-top: 10px;
    }

    .utterance-note, .utterance-play, .utterance-bars {
        color: #676a6c;
        cursor: pointer;
        display: inline-block;
    }

    .utterance-bars {
        vertical-align: middle;
    }

    #single_key_elements {
        display: block;
    }

    #multi_key_elements {
        display: none;
    }

    .key-elements-edit {
        color: #676a6c;
        cursor: pointer;
        vertical-align: middle;
    }

    .summary_container {
        background-color: #e9ecef;
    }
        /* .summary_container table {
            border-bottom: 1px solid transparent !important;
        }*/

        .summary_container tr:last-child td {
            border-bottom: 1px solid transparent !important;
        }

        .summary_container .title {
            color: black;
            font-size: 18px;
        }

        .summary_container .consent_content_wrapper {
            margin-top: 15px;
        }

            .summary_container .consent_content_wrapper .col-sm-2 {
                padding-right: 0px;
            }
    
        .summary_container .consent_container {
            width: 100%;
            background: #fff;
            border-radius: 6px;
            margin-top: 10px;
            padding: 13px 15px 3px 15px;
            box-shadow: 1px 1px 3px rgb(0 0 0 / 20%);
        }
</style>
<div class="wrapper animated fadeInRight">
    <div>&nbsp;</div>
    @*<div class="table-responsive">
            <table class="table table-bordered text-center custmer-consent">
                <tr>
                    <td colspan="4"><span>CUSTOMER CONSENT</span></td>
                </tr>
                <tr>
                    <td>
                        <h3 class="p-enrollment">&nbsp;</h3>
                        <h5 class="p-consent">&nbsp;</h5>
                    </td>
                    <td>
                        <h3 class="p-score">0%</h3>
                        <h5 class="p-match">MATCH</h5>
                    </td>
                </tr>
            </table>
        </div>*@

    <div><a href="CallRecordingAnalysisIndex"><i class="fa fa-chevron-left fa-lg" aria-hidden="true"></i></a></div>

    <div>&nbsp;</div>

    <div class="row">
        <div class="col-sm-9">
            <button class="btn btn-default" type="button" data-toggle="collapse" data-target="#collapse_recordings" aria-expanded="false" aria-controls="collapse_recordings">
                <span>All recordings</span>&nbsp;<span class="caret"></span>
            </button>

            &nbsp;
            <div id="btnToggleViewButton" class="btn-group">
                <button class="btn btn-primary single" type="button">
                    <i class='fa fa-tasks'></i>&nbsp;&nbsp;Single View
                </button>
                <button class="btn btn-white combine" type="button">
                    <i class='fa fa-th'></i>&nbsp;&nbsp;Combined View
                </button>
            </div>

            <div class="collapse" id="collapse_recordings">
                <div id="searchDiv" style="display:none;">
                    <input id="customer_name" col="customer_name" type="hidden" />
                </div>
                <div class="select-table table-striped" style="padding:5px 15px;">
                    <table id="gridTable" data-mobile-responsive="true"></table>
                </div>
                <div>&nbsp;</div>
            </div>
        </div>
    </div>

    <div>&nbsp;</div>

    <div id="waveform_wrapper" style="height: 220px">
        <div id="waveform" style="position:relative">
            <div id="waveform_loading" style="position: absolute; top: 80px; left: 40%; display:none">
                <div class="loaderbox">
                    <div class="loading-activity"></div>
                    &nbsp;&nbsp;loading audio control...
                </div>
            </div>
        </div>
        <div id="wave-timeline"></div>
        <div id="waveform_action_form" style="margin-top:20px; text-align:center; display:none">
            <button id="waveform_action_button" class="btn btn-success" data-action="play">
                <i class="glyphicon glyphicon-play"></i>
                Play
                /
                <i class="glyphicon glyphicon-pause"></i>
                Pause
            </button>
        </div>
    </div>

    <div>
        <div class="row">
            <div id="call_transcript" class="col-sm-9">
                <ul class="nav nav-tabs" role="tablist">
                    <li role="presentation" class="active"><a href="#transcript_tab" aria-controls="transcript_tab" role="tab" data-toggle="tab">TRANSCRIPT</a></li>
                    <li role="presentation"><a href="#summary_tab" aria-controls="summary_tab" role="tab" data-toggle="tab">SUMMARY</a></li>
                </ul>

                <div class="tab-content">
                    <div role="tabpanel" class="tab-pane active" id="transcript_tab">
                        <div class="panel panel-default transcript_container">
                            @*<div class="panel-heading">
                                    TRANSCRIPT
                                </div>*@

                            <div class="panel-line">
                                <hr />
                            </div>

                            <div class="panel-body">
                                <div id="compare_result">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div role="tabpanel" class="tab-pane" id="summary_tab">
                        <div class="panel panel-default summary_container">

                            <div class="panel-body">
                                <div class="key-elements">
                                    <div class="title">
                                        Key Elements:
                                    </div>
                                    <div id="single_key_elements" class="select-table table-striped" style="padding:5px 15px 15px 15px">
                                        <table id="gridTableKeyElements" class="key-elements-table" data-mobile-responsive="true"></table>
                                    </div>
                                    @*<div id="multi_key_elements" class="select-table table-striped" style="padding:15px;"></div>*@
                                </div>
                                <div class="consent_content_wrapper customer_consent_container">
                                    <div class="title">
                                        Customer Consent:
                                    </div>
                                    <div class="consent_container">
                                        <p class="customer_consent_content">
                                        </p>
                                        <p>
                                            Customer Answer: <span class="customer_consent_answer"></span>
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper pcp_container">
                                    <div class="title">
                                        PCP:
                                    </div>
                                    <div class="consent_container">
                                        <p class="pcp_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper callecorded_container">
                                    <div class="title">
                                        Permission to Record:
                                    </div>
                                    <div class="consent_container">
                                        <p class="callrecorded_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper callback_container">
                                    <div class="title">
                                        Call Back Permission if disconnected:
                                    </div>
                                    <div class="consent_container">
                                        <p class="callback_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper futurecall_container">
                                    <div class="title">
                                        Future Call Permission:
                                    </div>
                                    <div class="consent_container">
                                        <p class="futurecall_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper appointment_container">
                                    <div class="title">
                                        Scope of Appointment:
                                    </div>
                                    <div class="consent_container">
                                        <p class="appointment_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper medicare_container">
                                    <div class="title">
                                        Medicare Advantage Disclaimer:
                                    </div>
                                    <div class="consent_container">
                                        <p class="medicare_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper rx_container">
                                    <div class="title">
                                        RX Restriction:
                                    </div>
                                    <div class="consent_container">
                                        <p class="rx_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper inboundcallback_container">
                                    <div class="title">
                                        Enrollment Inbound Callback:
                                    </div>
                                    <div class="consent_container">
                                        <p class="inboundcallback_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper specialistinnetwork_container">
                                    <div class="title">
                                        Specialist in network:
                                    </div>
                                    <div class="consent_container">
                                        <p class="specialistinnetwork_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper pcpcopay_container">
                                    <div class="title">
                                        PCP co-pay / co-insurance:
                                    </div>
                                    <div class="consent_container">
                                        <p class="pcpcopay_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper specialistcopay_container">
                                    <div class="title">
                                        Specialist co-pay / co-insurance:
                                    </div>
                                    <div class="consent_container">
                                        <p class="specialistcopay_content">
                                        </p>
                                    </div>
                                </div>
                                @*<div class="consent_content_wrapper pcpcoinsurance_container">
                                    <div class="title">
                                        PCP co-insurance:
                                    </div>
                                    <div class="consent_container">
                                        <p class="pcpcoinsurance_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper specialistcoinsurance_container">
                                    <div class="title">
                                        Specialist co-insurance:
                                    </div>
                                    <div class="consent_container">
                                        <p class="specialistcoinsurance_content">
                                        </p>
                                    </div>
                                </div>*@
                                <div class="consent_content_wrapper drugtiers_container">
                                    <div class="title">
                                        Drug Tiers:
                                    </div>
                                    <div class="consent_container">
                                        <p class="drugtiers_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper hospitalcopay_container">
                                    <div class="title">
                                        Hospital co-pay / co-insurance:
                                    </div>
                                    <div class="consent_container">
                                        <p class="hospitalcopay_content">
                                        </p>
                                    </div>
                                </div>
                                @*<div class="consent_content_wrapper hospitalcoinsurance_container">
                                    <div class="title">
                                        Hospital co-insurance:
                                    </div>
                                    <div class="consent_container">
                                        <p class="hospitalcoinsurance_content">
                                        </p>
                                    </div>
                                </div>*@
                                <div class="consent_content_wrapper premium_container">
                                    <div class="title">
                                        Premium:
                                    </div>
                                    <div class="consent_container">
                                        <p class="premium_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper maxoutofpocket_container">
                                    <div class="title">
                                        Max out of pocket:
                                    </div>
                                    <div class="consent_container">
                                        <p class="maxoutofpocket_content">
                                        </p>
                                    </div>
                                </div>
                                <div class="consent_content_wrapper">
                                    <div class="title">
                                        Call Notes:
                                    </div>
                                    <div id="searchDivNotes" style="display:none;">
                                        <input id="use_pagination" col="use_pagination" type="hidden" value="1" />
                                    </div>
                                    <div class="select-table table-striped" style="padding:5px 15px;">
                                        <table id="gridTableNotes" data-mobile-responsive="true"></table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div>&nbsp;</div>

                <div id="new_comment">
                    <div id="add_new_comment" class="row">
                        <div class="col-sm-1">
                            <div class="text-right">
                                <img class="img-circle comment-avatar-lg" src="/image/portrait.png" />
                            </div>
                        </div>
                        <div class="col-sm-11">
                            <div class="comment-trigger">
                                <input type="text" class="form-control" id="txtNewComment" placeholder="Add a comment...">
                            </div>
                            <div class="comment-cta" style="display:none;">
                                <div id="comment_editor"></div>
                                <div id="comment_msg" class="text-danger"></div>
                                <div>
                                    <input id="btnAddComment" type="button" class="btn btn-primary" value="Save" />&nbsp;&nbsp;
                                    <input id="btnCancelComment" type="button" class="btn btn-default" value="Cancel" />
                                </div>
                            </div>
                        </div>
                    </div>

                    <table style="border:0px solid white !important; width:100%;">
                        <tr>
                            <td style="vertical-align:top; width:50px;">
                            </td>
                            <td>
                            </td>
                        </tr>
                    </table>

                    <div id="comments_anchor">&nbsp;</div>

                    <section id="comments_section" style="display:none;">
                        <h4>Comments</h4>
                        <div id="comment_list"></div>
                    </section>

                    <script id="comment_template" type="text/template">
                        <div class="comment-item">
                            <div class="comment-heading">
                                <img class="img-circle comment-avatar" src="/image/portrait.png" />
                                <span class="comment-author">{author}</span>&nbsp;-&nbsp;<span class="comment-time">{time}</span>
                                <span class="comment-text">{txt}</span>
                            </div>
                            <div class="comment-body">{html}</div>
                        </div>
                    </script>
                </div>

                <div>&nbsp;</div>
            </div>
            <div id="call_info" class="col-sm-3">
                <div class="call-info">
                    <p>
                        <label>Customer Name:</label>
                        <br />
                        <span class="customer_name"></span>
                    </p>
                    <p>
                        <label>Call Purpose:</label>
                        <br />
                        <span class="p-enrollment"></span>
                    </p>
                    <p>
                        <label>Customer Consent:</label>
                        <br />
                        <span class="p-customer-score"></span>
                    </p>
                    <p>
                        <label>Timestamp of Customer Consent:</label>
                        <br />
                        <span class="customer_consent_timestamp"></span>
                    </p>
                    <p>
                        <label>Time of Call:</label>
                        <br />
                        <span class="time_of_call"></span>
                    </p>
                    <p>
                        <label>Length of Call:</label>
                        <br />
                        <span class="length_of_call"></span>
                    </p>
                    <p>
                        <label>Call Center:</label>
                        <br />
                        <span class="call_center"></span>
                    </p>
                    <p>
                        <label>Agent Name:</label>
                        <br />
                        <span class="agent_name"></span>
                    </p>
                    <p>
                        <label>Recording #:</label>
                        <br />
                        <span class="recording-id"></span>
                    </p>
                    <p>
                        <label>File:</label>
                        <br />
                        <span class="recording-file"></span>
                    </p>

                    <div style="margin-top: 10px">
                        <button id="btnSwitchSpeakerLabel" class="btn btn-default">
                            <span>Switch Speaker Label</span>
                        </button>
                    </div>
                    @*<div style="margin-top: 10px">
                        <button id="btnReprocessTextMatcher" class="btn btn-default">
                            <span>Manual Re-process</span>
                        </button>
                    </div>
                    <div style="margin-top: 10px">
                        <label>Re-Process Status:</label>
                        <br />
                        <span class="text_matcher_status"></span>
                    </div>*@
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    var id = ys.request("id");
    var recording_id = 0;
    var is_combined_view = false;
    var combined_recording_param = "";
    var combined_recording_ids = [];
    var has_comment_editor = false;
    var wavesurfer_ready = false;
    var init_summary_tab = false;
    var refresh_notes_table = false;

    $(function () {

        getDetail();

        $('#btnToggleViewButton').on('click', '.btn', function () {

            if ($(this).hasClass('btn-primary')) {
                return;
            }
            $(this).addClass('btn-primary').removeClass('btn-white').siblings().addClass('btn-white').removeClass('btn-primary');

            if ($(this).hasClass('single')) {
                is_combined_view = false;
            } else {
                is_combined_view = true;
            }

            init_summary_tab = false;
            wavesurfer.destroy();
            $("#waveform_action_form").hide();
            $(".key-elements-table").bootstrapTable('destroy');
            $("#multi_key_elements").empty();

            getDetail();
        });

        $("#btnBack").click(function () {
            self.location.href = 'CallRecordingAnalysisIndex';
        });

        $("#btnSwitchSpeakerLabel").click(function () {
            ys.confirm("Are you sure that you want to switch speaker label?", function () {
                var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SwitchSpeakerLabel")';
                var data = {
                    recording_id: recording_id
                };

                ys.ajax({
                    url: url,
                    type: 'post',
                    data: data,
                    success: function (obj) {
                        if (obj.Tag == 1) {
                            self.location.href = 'CallRecordingAnalysisDetail?id=' + id;
                            return;
                        }
                    }
                });
            });
        });

        $("#btnReprocessTextMatcher").click(function () {
            ys.confirm("Are you sure that you want to reprocess this recording? This may take sometime.", function () {
                var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/ReprocessTextMatcher")';
                var data = {
                    recording_id: recording_id
                };

                ys.ajax({
                    url: url,
                    type: 'post',
                    data: data,
                    success: function (obj) {
                        //if (obj.Tag == 1) {
                        //    //ys.alertSuccess("This may take sometimes. You need to refresh the page to get the new result.");
                        //    //self.location.href = 'CallRecordingAnalysisDetail?id=' + id;
                        //    if (!ys.alertSuccess('This may take sometimes.')) { window.location.reload(); }
                        //    return;
                        //}
                        if (obj.Tag == 1) {
                            self.location.href = 'CallRecordingAnalysisDetail?id=' + id;
                            return;
                        }
                    }
                });
            });
        });

        $("#waveform_action_button").click(function () {
            current_utterance_play_start = -1;
            if (wavesurfer.isPlaying()) {
                wavesurfer.pause();
            } else {
                wavesurfer.play();
            }
        });

        $(document).on("click", "#gridTable tbody tr", function () {
            var uniqueid = $(this).data('uniqueid');
            viewDetails(uniqueid);
        });

        var current_utterance_play_start = -1;
        $(document).on("click", "#compare_result .utterance-play", function () {
            if (wavesurfer_ready) {
                
                var start = $(this).data('start');
                var end = $(this).data('end');

                if (current_utterance_play_start == start) {

                    if (wavesurfer.isPlaying()) {
                        wavesurfer.pause();
                    } else {
                        wavesurfer.play(parseFloat(start));
                        current_utterance_play_start = start;
                    }

                } else {

                    if (wavesurfer.isPlaying()) {
                        wavesurfer.pause();
                    }

                    wavesurfer.play(parseFloat(start));
                    current_utterance_play_start = start;
                }
            }
        });

        $(".nav-tabs li").click(function () {
            if ($(this).text() == "SUMMARY") {
                if (!init_summary_tab) {
                    initGridNotes();
                    init_summary_tab = true;
                } else if (refresh_notes_table) {
                    $('#gridTableNotes').ysTable('search');
                    refresh_notes_table = false;
                }
            }
        });

        $('#comment_editor').summernote({
            height: 100,
            dialogsInBody: true,
            placeholder: "Add a comment...",
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline']],
                ['fontname', ['fontname']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['codeview']]
            ]
        });

        $("#txtNewComment").click(function () {
            $(".comment-trigger").hide();
            $(".comment-cta").slideDown(200, function () {
                setTimeout(function () {
                    //$("body").scrollTop($("#comments_anchor").position().top);
                    $("#btnAddComment").focus();
                    $("#comment_editor").summernote("focus");
                }, 0);
            });
        });

        $("#btnAddComment").click(function () {
            if (recording_id > 0) {
                if ($('#comment_editor').summernote('isEmpty')) {
                    //ys.alertWarning("Comment can't be empty");
                    //$("#comment_msg").text("Comment can't be empty");
                    return;
                }

                $("#comment_msg").text("");

                var $this = $(this);

                $this.prop("disabled", true);

                var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SaveRecordingComment")';
                var comment_html = $("#comment_editor").summernote('code');
                var data = {
                    recording_id: recording_id,
                    comment_html: comment_html
                };

                $.post(url, data, function (obj) {
                    if (obj.Tag == 1) getComments();
                }).always(function () {
                    $('#comment_editor').summernote('reset');
                    $this.prop("disabled", false);
                });
            }
        });

        $("#btnCancelComment").click(function () {
            $('#comment_editor').summernote('reset');
            $(".comment-cta").hide();
            $(".comment-trigger").show();
        });
    });

    function getDetail() {

        var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/GetDetailJson")';

        if (!is_combined_view) {

            url += '?id=' + id;

        } else {

            var customer_name = $("#customer_name").val();
            url += '?customer_name=' + customer_name;
        }

        if (id > 0) {
            ys.ajax({
                url: url,
                type: 'get',
                success: function (obj) {
                    if (obj.Tag == 1) {
                        recording_id = obj.Data.recording_id;
                        combined_recording_param = obj.Data.combined_recording_param || "";
                        combined_recording_ids = is_combined_view ? combined_recording_param.split(',').map(
                            x => x.split('||')[0]).filter(y => y != '') : [recording_id];

                        $('#compare_result').empty().html(obj.Data.compare_result);

                        fillProperties(obj);
                        initWaveTimeLine(obj);
                        initGrid(obj);

                        initAnnotations(obj).then(result => {
                            setTimeout(function () {
                                moveToCustomerConsentLocation($(".macthed_text"));
                            }, 0);
                        });

                        getComments();
                        getUtteranceNotes();

                        setTimeout(initUtterancePopover, 0);
                    }
                }
            });
        }
    }

    function viewDetails(id) {
        self.location.href = 'CallRecordingAnalysisDetail?id=' + id;
        return;

        ys.openDialog({
            title: 'Details',
            content: '@Url.Content("~/BusinessManage/CallRecordingAnalysis/CallRecordingAnalysisDetail")' + '?id=' + id,
            width: '768px',
            height: '640px',
            callback: function (index, layero) {
                layer.close(index);
            }
        });
    }

    function initGrid(obj) {
        $("#customer_name").val(obj.Data.customer_name);

        var queryUrl = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/GetPageListJson")';
        $('#gridTable').ysTable({
            url: queryUrl,
            sortName: 'c.time_of_call',
            sortOrder: 'desc',
            clickToSelect: true,
            pagination: true,
            toolbar: false,
            showColumns: false,
            showRefresh: false,
            showToggle: false,
            columns: [
                { field: 'customer_name', title: 'Customer Name', sortable: false, sortName: 'c.customer_name' },
                {
                    field: 'is_enrollment', title: 'Call Purpose', sortable: false, sortName: 'b.is_enrollment',
                    formatter: function (value, item, index) {
                        if (value == "1") {
                            return '<span class="label label-success">Enrollment</span>';
                        }
                        else if (value == "0") {
                            return '<span class="label label-warning">Pre-enrollment</span>';
                        }
                        else {
                            return '<span class="label label-warning">Pre-enrollment</span>';
                        }
                    }
                },
                { field: 'time_of_call', title: 'time_of_call_value', visible: false },
                { field: 'time_of_call_text', title: 'Time of Call', sortable: false, sortName: 'c.time_of_call' },
                { field: 'agent_name', title: 'Agent Name', sortable: false, sortName: 'c.agent_name' }
            ],
            queryParams: function (params) {
                var pagination = $('#gridTable').ysTable('getPagination', params);
                var queryString = $('#searchDiv').getWebControls(pagination);
                return queryString;
            }
        });
    }

    function fillProperties(obj) {
        var is_enrollment = obj.Data.is_enrollment;
        var has_customerconsent = obj.Data.has_customerconsent;
        var similiarity_score = obj.Data.similiarity_score;
        var customer_consent_score = obj.Data.customer_consent_score;

        if (is_combined_view) {
            $("#call_transcript").removeClass('col-sm-9').addClass('col-sm-11');
            $("#call_info").hide();
            $("#add_new_comment").hide();
        } else {
            $("#call_transcript").removeClass('col-sm-11').addClass('col-sm-9');
            $("#call_info").show();
            $("#add_new_comment").show();
        }

        $(".recording-id").text(obj.Data.recording_id);
        $(".recording-file").text(obj.Data.recording_file);

        $(".call_center").text(obj.Data.call_center);
        $(".time_of_call").text(obj.Data.time_of_call_text);
        $(".length_of_call").text(obj.Data.length_of_call);
        $(".agent_name").text(obj.Data.agent_name);
        $(".customer_name").text(obj.Data.customer_name);
        $(".customer_consent_timestamp").text(obj.Data.customer_consent_timestamp);
        $(".customer_timestamp").text(obj.Data.customer_timestamp);
        $(".pcp_timestamp").text(obj.Data.pcp_timestamp);
        $(".callrecorded_timestamp").text(obj.Data.callrecorded_timestamp);

        $(".p-results").text("");
        $(".p-words").text(obj.Data.matchedwords);

        if (is_enrollment == "1") {
            $(".p-enrollment").text("Enrollment");
        }
        else if (is_enrollment == "0") {
            $(".p-enrollment").text("Pre-Enrollment");
        }
        else {

        }

        if (has_customerconsent == "1") {
            $(".p-consent").addClass("text-navy").text("WITH CUSTOMER CONSENT");
        }
        else if (has_customerconsent == "0") {
            $(".p-consent").addClass("text-warning").text("NO CUSTOMER CONSENT");
        }
        else {

        }

        if (similiarity_score != "") {

            if (similiarity_score != "N/A") {
                similiarity_score += "%";
            }

            //$(".p-score, .p-match").addClass("text-navy");
            $(".p-score").text(similiarity_score);
        }

        if (customer_consent_score != "" && customer_consent_score != null) {

            if (customer_consent_score != "N/A") {
                customer_consent_score += "%";
            }

            $(".p-customer-score").text(customer_consent_score);
        }

        if (obj.Data.all_prcoessed > 0) {
            $(".text_matcher_status").addClass("text-navy").text("Completed");
        } else {
            $(".text_matcher_status").addClass("text-warning").text("In Process");
        }

        $(".consent_content_wrapper").show();

        if (customer_consent_score != "" && customer_consent_score != null && customer_consent_score != "N/A") {
            //$(".customer_consent_content").text($("#compare_result .macthed_text").text());
            $(".customer_consent_content").html(obj.Data.customer_consent_content);
            $(".customer_consent_answer").text(obj.Data.customer_consent_answer);
        } else {
            $(".customer_consent_container").hide();
        }

        if (obj.Data.pcp_content != "") {
            //$(".pcp_content").text($("#compare_result .macthed_text_pcp").text());
            $(".pcp_content").html(obj.Data.pcp_content);
        } else {
            $(".pcp_container").hide();
        }

        if (obj.Data.callrecorded_content != "") {
            //$(".callrecorded_content").text($("#compare_result .macthed_text_callrecorded").text());
            $(".callrecorded_content").html(obj.Data.callrecorded_content);
        } else {
            $(".callecorded_container").hide();
        }

        if (obj.Data.callback_content != "") {
            $(".callback_content").html(obj.Data.callback_content);
        } else {
            $(".callback_container").hide();
        }

        if (obj.Data.futurecall_content != "") {
            $(".futurecall_content").html(obj.Data.futurecall_content);
        } else {
            $(".futurecall_container").hide();
        }

        if (obj.Data.appointment_content != "") {
            $(".appointment_content").html(obj.Data.appointment_content);
        } else {
            $(".appointment_container").hide();
        }

        if (obj.Data.medicare_content != "") {
            $(".medicare_content").html(obj.Data.medicare_content);
        } else {
            $(".medicare_container").hide();
        }

        if (obj.Data.rx_content != "") {
            $(".rx_content").html(obj.Data.rx_content);
        } else {
            $(".rx_container").hide();
        }

        if (obj.Data.inboundcallback_content != "") {
            $(".inboundcallback_content").html(obj.Data.inboundcallback_content);
        } else {
            $(".inboundcallback_container").hide();
        }

        if (obj.Data.specialistinnetwork_content != "") {
            $(".specialistinnetwork_content").html(obj.Data.specialistinnetwork_content);
        } else {
            $(".specialistinnetwork_container").hide();
        }

        if (obj.Data.pcpcopay_content != "") {
            $(".pcpcopay_content").html(obj.Data.pcpcopay_content);
        } else {
            $(".pcpcopay_container").hide();
        }

        if (obj.Data.specialistcopay_content != "") {
            $(".specialistcopay_content").html(obj.Data.specialistcopay_content);
        } else {
            $(".specialistcopay_container").hide();
        }

        if (obj.Data.drugtiers_content != "") {
            $(".drugtiers_content").html(obj.Data.drugtiers_content);
        } else {
            $(".drugtiers_container").hide();
        }

        if (obj.Data.hospitalcopay_content != "") {
            $(".hospitalcopay_content").html(obj.Data.hospitalcopay_content);
        } else {
            $(".hospitalcopay_container").hide();
        }

        if (obj.Data.premium_content != "") {
            $(".premium_content").html(obj.Data.premium_content);
        } else {
            $(".premium_container").hide();
        }

        if (obj.Data.maxoutofpocket_content != "") {
            $(".maxoutofpocket_content").html(obj.Data.maxoutofpocket_content);
        } else {
            $(".maxoutofpocket_container").hide();
        }

        if (obj.Data.pcpcoinsurance_content != "") {
            $(".pcpcoinsurance_content").html(obj.Data.pcpcoinsurance_content);
        } else {
            $(".pcpcoinsurance_container").hide();
        }

        if (obj.Data.specialistcoinsurance_content != "") {
            $(".specialistcoinsurance_content").html(obj.Data.specialistcoinsurance_content);
        } else {
            $(".specialistcoinsurance_container").hide();
        }

        if (obj.Data.hospitalcoinsurance_content != "") {
            $(".hospitalcoinsurance_content").html(obj.Data.hospitalcoinsurance_content);
        } else {
            $(".hospitalcoinsurance_container").hide();
        }

        initKeyElements(obj);
    }

    function initKeyElements(obj) {

        $("#single_key_elements").show();
        initKeyElementsGrid('gridTableKeyElements', obj);

        //$("#single_key_elements").hide();
        //$("#multi_key_elements").hide();

        //if (combined_recording_ids.length == 1) {
        //    $("#single_key_elements").show();

        //    initKeyElementsGrid('gridTableKeyElements', recording_id, obj);

        //    return;
        //}

        //if (combined_recording_ids.length > 1) {
        //    $("#multi_key_elements").show();

        //    var $ul = $('<ul class="nav nav-tabs" role="tablist"/>');
        //    var $tabs = $('<div class="tab-content"/>');
        //    var table_ids = [];

        //    for (var i = 0; i < combined_recording_ids.length; i++) {
        //        var id = combined_recording_ids[i];
        //        var tab_id = "ke_tab" + id;
        //        var $li = $(
        //            [
        //                '<li role="presentation" class="',
        //                (i == 0 ? 'active' : ''),
        //                '"> <a href="',
        //                "#" + tab_id,
        //                '" aria-controls="',
        //                tab_id,
        //                '" role="tab" data-toggle="tab">Recording #',
        //                id,
        //                '</a></li>'
        //            ].join(''));

        //        var $tab = $(
        //            [
        //                '<div role="tabpanel" class="tab-pane ',
        //                (i == 0 ? 'active' : ''),
        //                '" id="',
        //                tab_id,
        //                '"></div>'
        //            ].join(''));

        //        var table_id = 'ke_table' + id;
        //        var $table = $('<table id="' + table_id + '" class="key-elements-table" data-mobile-responsive="true"></table>');

        //        $tab.append($table);
        //        $ul.append($li);
        //        $tabs.append($tab);

        //        table_ids.push(table_id);
        //    }

        //    $("#multi_key_elements").append($ul).append($tabs);

        //    for (var i = 0; i < table_ids.length; i++) {
        //        initKeyElementsGrid(table_ids[i], combined_recording_ids[i], obj);
        //    }

        //    return;
        //}
    }

    function initKeyElementsGrid(grid, obj) {
        var keyElementsCols = [
            { field: 'intent_id', title: '' },
            { field: 'intent', title: 'Intent' },
            {
                field: 'has_found', title: '',
                formatter: function (value, item, index) {
                    if (value == "1") {
                        return '<span class="label label-success">Found</span>';
                    }
                    else if (value == "0") {
                        return '<span class="label label-warning">No found</span>';
                    }
                    else {
                        return '<span></span>';
                    }
                }
            },
            { field: 'score', title: 'Score' },
            { field: 'timestamp', title: 'Timestamp' }
        ];

        if (is_combined_view) {
            keyElementsCols.splice(5, 0, { field: 'timeofcall', title: 'Time of call' });
        } else {
            keyElementsCols.splice(5, 0, {
                formatter: function (value, item, index) {
                    return '<a href="javascript:void(0);" class="key-elements-edit" data-unique-id="' + item.id + '"><i class="fa fa-edit"></i></a>';
                }
            });
        }

        $('#' + grid).ysTable({
            uniqueId: "id",
            data: obj.Data.keyElements,
            clickToSelect: false,
            pagination: false,
            toolbar: false,
            showColumns: false,
            showRefresh: false,
            showToggle: false,
            striped: false,
            columns: keyElementsCols,
            onPostBody: function () {
                initKeyElementsEdit(grid);
            }
        });
    }

    function initKeyElementsEdit(grid) {
        var $grid = $("#" + grid);

        $grid.find(".key-elements-edit").off("click").on("click", function () {
            var row_data = $grid.bootstrapTable("getRowByUniqueId", $(this).data("unique-id"));

            if (row_data) {
                var layer_html = $("#edit_recordingintent_template").html();

                ys.openDialogContent({ content: layer_html, width: '600px', height: 'auto' });

                setTimeout(function () {
                    $("#lblRecordingIntent").text("Intent - " + row_data.intent);
                    $("#ddlRecordingIntentFinding").val(row_data.has_found);

                    if (row_data.scoreable == 1)
                        $("#txtRecordingIntentScore").val(row_data.similiarity_score).prop("disabled", false);
                    else
                        $("#txtRecordingIntentScore").val("N/A").prop("disabled", true);

                    $("#btnUpdateRecordingIntent").off("click").on("click", function () {
                        var $this = $(this);
                        var similiarity_score = row_data.similiarity_score;
                        var has_found = row_data.has_found;

                        $("#txtRecordingIntentScore").removeClass("error");

                        if (row_data.scoreable == 1) {
                            var score = parseFloat($("#txtRecordingIntentScore").val());

                            if (score >= 0 && score <= 100) {
                                // Possible loss of precision but acceptable?
                                score = score.toFixed(2);

                                row_data.score = score + "%";
                                row_data.similiarity_score = score;
                            }
                            else {
                                $("#txtRecordingIntentScore").addClass("error");
                                return;
                            }
                        }

                        row_data.has_found = $("#ddlRecordingIntentFinding").val();

                        if (similiarity_score == row_data.similiarity_score && has_found == row_data.has_found) {
                            layer.close($this.closest(".layui-layer-page").attr("times"));
                            return;
                        }

                        $this.prop("disabled", true);

                        var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SaveRecordingIntent")';
                        var data = {
                            recording_id: row_data.recording_id,
                            intent_id: row_data.intent_id,
                            similiarity_score: row_data.similiarity_score,
                            has_found: row_data.has_found
                        };

                        var saved = false;

                        $.post(url, data, function (obj) {
                            if (obj.Tag == 1) saved = true;
                        }).always(function () {
                            if (saved) {
                                $this.prop("disabled", false);
                                $grid.bootstrapTable("updateByUniqueId", { id: row_data.id, row: row_data });
                                layer.close($this.closest(".layui-layer-page").attr("times"));
                            }
                        });
                    });

                    $("#btnCancelRecordingIntent").off("click").on("click", function () {
                        layer.close($(this).closest(".layui-layer-page").attr("times"));
                    });
                }, 500);
            }
        });
    }

    var wavesurfer;
    //var wave_markers = [];
    function initWaveTimeLine(obj) {

        $("#waveform_loading").show();
        $("#waveform_action_form").hide();

        var wav_url = obj.Data.wav_url;
        var markers = [];

        if (obj.Data.wav_markers && obj.Data.wav_markers.length > 0) {

            //wave_markers = obj.Data.wav_markers;

            for (var i = 0; i < obj.Data.wav_markers.length; i++) {
                var marker = new Object();
                marker.time = obj.Data.wav_markers[i].time;
                marker.label = obj.Data.wav_markers[i].label;
                marker.color = obj.Data.wav_markers[i].color;
                marker.position = obj.Data.wav_markers[i].position;
                markers.push(marker);
            }

        }

        //wavesurfer = WaveSurfer.create({
        //    container: document.querySelector('#waveform'),
        //    //pixelRatio: 1,
        //    minPxPerSec: 3,
        //    //hideScrollbar: true,
        //    scrollParent: true,
        //    //normalize: true,
        //    waveColor: 'darkcyan',
        //    plugins: [
        //        WaveSurfer.markers.create({
        //            markers: markers
        //        }),
        //        WaveSurfer.timeline.create({
        //            container: "#wave-timeline"
        //        })
        //    ]
        //});

        wavesurfer = WaveSurfer.create({
            container: document.querySelector('#waveform'),
            //pixelRatio: 1,
            //minPxPerSec: 3,
            hideScrollbar: true,
            scrollParent: false,
            //normalize: true,
            waveColor: 'darkcyan',
            plugins: [
                WaveSurfer.markers.create({
                    markers: markers
                }),
                WaveSurfer.timeline.create({
                    container: "#wave-timeline"
                })
            ]
        });

        //wavesurfer.load('http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');
        wavesurfer.load(wav_url);

        wavesurfer.on('ready', function () {
            $("#waveform_loading").hide();
            $("#waveform_action_form").show();
            wavesurfer_ready = true;
            //wavesurfer.seekAndCenter(0.6);

            //$(".wavesurfer-marker span").css('visibility', 'visible');

            $('.wavesurfer-marker').each(function (i, obj) {
                var left = $(this).css('left').replace('px', '');
                var offset = parseInt(left) + 40;
                //var offset = parseInt(left) + 30;
                $(this).find('span').css('left', offset + 'px');
            });

        });

        wavesurfer.on('marker-click', function (obj) {
            if (!wavesurfer.isPlaying()) {
                wavesurfer.play();
            }

            if (obj.label.indexOf("Agent Asking For Consent") >= 0) {
                var $move_element = $(".macthed_text");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("PCP in network") >= 0) {

                var $move_element = $(".macthed_text_pcp");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Permission to Record") >= 0) {

                var $move_element = $(".macthed_text_callrecorded");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Call Back Permission if disconnected") >= 0) {

                var $move_element = $(".macthed_text_callback");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Future Call Permission") >= 0) {

                var $move_element = $(".macthed_text_futurecall");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Scope of Appointment") >= 0) {

                var $move_element = $(".macthed_text_appointment");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Medicare Advantage Disclaimer") >= 0) {

                var $move_element = $(".macthed_text_medicare");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("RX Restriction") >= 0) {

                var $move_element = $(".macthed_text_rx");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Enrollment Inbound Callback") >= 0) {

                var $move_element = $(".macthed_text_inboundcallback");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Specialist in network") >= 0) {

                var $move_element = $(".macthed_text_specialistinnetwork");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("PCP co-pay / co-insurance") >= 0) {

                var $move_element = $(".macthed_text_pcpcopay");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Specialist co-pay / co-insurance") >= 0) {

                var $move_element = $(".macthed_text_specialistcopay");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Drug Tiers") >= 0) {

                var $move_element = $(".macthed_text_drugtiers");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Hospital co-pay / co-insurance") >= 0) {

                var $move_element = $(".macthed_text_hospitalcopay");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Premium") >= 0) {

                var $move_element = $(".macthed_text_premium");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Max out of pocket") >= 0) {

                var $move_element = $(".macthed_text_maxoutofpocket");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("PCP co-insurance") >= 0) {

                var $move_element = $(".macthed_text_pcpcoinsurance");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Specialist co-insurance") >= 0) {

                var $move_element = $(".macthed_text_specialistcoinsurance");
                moveToCustomerConsentLocation($move_element);
            }

            if (obj.label.indexOf("Hospital co-insurance") >= 0) {

                var $move_element = $(".macthed_text_hospitalcoinsurance");
                moveToCustomerConsentLocation($move_element);
            }

        });

    }

    function moveToCustomerConsentLocation($move_element) {

        //var $callinfoDiv = $('.call-info');
        var $parentDiv = $('#compare_result');
        var $mactched_Item = $move_element.first().closest('.row');

        $parentDiv.scrollTop(0);

        if ($mactched_Item.size() > 0) {
            //var offset = $mactched_Item.position().top - $parentDiv.height() / 2;
            var offset = $mactched_Item.position().top - 100;
            $parentDiv.scrollTop(offset);
        }

    }

    function getComments() {
        if (recording_id > 0) {
            var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/GetRecordingComments")';

            if (!is_combined_view) {
                url += '?recordingId=' + recording_id;
            } else {
                url += '?combined_recording_param=' + combined_recording_param;
            }

            var comments = [];

            $.get(url, function (obj) {
                if (obj.Tag == 1) comments = obj.Data;
            }).always(function () {
                var list = $("#comment_list");
                var template = $("#comment_template").html();

                $("#comments_section").hide();
                list.empty();

                $.each(comments, function (index, item) {
                    var hc = $("<div/>").html(item.comment_html);

                    $("<div/>").html(template.replace("{author}", item.commenter)
                        .replace("{time}", item.created_at_text)
                        .replace("{txt}", hc.text())
                        .replace("{html}", hc.html())).appendTo(list);
                });

                if (comments.length > 0) $("#comments_section").show();
            });
        }
    }

    var utterance_note_time_start = "";
    var utterance_note_node = null;
    var utterance_note_list = [];

    function getUtteranceNotes() {
        // Note is processed somewhere else, do nothing here for now.
        return;

        @*utterance_note_time_start = "";
        utterance_note_node = null;
        utterance_note_list = [];

        if (recording_id > 0) {
            var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/GetUtteranceNotes")' + '?recordingId=' + recording_id;

            $.get(url, function (obj) {
                if (obj.Tag == 1) utterance_note_list = obj.Data;
            }).always(function () {
                u_notes = $("#compare_result").find(".utterance-note");

                $(u_notes).each(function () {
                    var $note = $(this);
                    var u_timestart = $note.data("timestart") || "u_timestart";

                    $note.addClass("fa fa-comment");

                    $.each(utterance_note_list, function (index, item) {
                        var time_start = item.time_start || "time_start";

                        if (time_start == u_timestart) $note.removeClass("fa-comment").addClass("fa-comments text-info");
                    });

                    $note.off("click").on("click", function () {
                        utterance_note_node = $note;
                        utterance_note_time_start = $note.data("timestart") || "";

                        if (utterance_note_time_start == "") return;

                        var layer_html = $("#add_utterance_note_template").html();
                        var layer_div = $("<div/>").html(layer_html);
                        var layer_notes = layer_div.find("#divUtteranceNote");
                        var layer_list = layer_div.find("#lstUtteranceNote");
                        var template = $("#utterance_note_template").html();

                        layer_notes.hide();
                        layer_list.empty();

                        $.each(utterance_note_list, function (index, item) {
                            if (item.time_start == utterance_note_time_start) {
                                var hc = $("<div/>").html(item.note_html);

                                $("<div/>").html(template.replace("{author}", item.noter)
                                    .replace("{time}", item.created_at_text)
                                    .replace("{txt}", hc.text())
                                    .replace("{html}", hc.html())).appendTo(layer_list);
                            }
                        });

                        if (utterance_note_list.length > 0) layer_notes.show();

                        layer_html = layer_div.html();

                        ys.openDialogContent({ content: layer_html, width: '600px', height: 'auto' });

                        setTimeout(function () {
                            $("#txtUtteranceNote").focus();
                            $("#btnAddUtteranceNote").off("click").on("click", function () {
                                if (recording_id > 0) {
                                    if (utterance_note_node == null || utterance_note_time_start == "") return;

                                    var note_html = $.trim($("#txtUtteranceNote").val() || "");

                                    if (note_html == "") {
                                        //$("#utterance_note_msg").text("Note can't be empty");
                                        return;
                                    }

                                    $("#utterance_note_msg").text("");

                                    var $this = $(this);

                                    $this.prop("disabled", true);

                                    var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SaveUtteranceNote")';
                                    var data = {
                                        recording_id: recording_id,
                                        time_start: utterance_note_time_start,
                                        note_html: note_html
                                    };

                                    $.post(url, data, function (obj) {
                                        if (obj.Tag == 1) {
                                            getUtteranceNotes();
                                            refresh_notes_table = true;
                                        }
                                    }).always(function () {
                                        $this.prop("disabled", false);
                                        layer.close($this.closest(".layui-layer-page").attr("times"));
                                    });
                                }
                            });

                            $("#btnCancelUtteranceNote").off("click").on("click", function () {
                                layer.close($(this).closest(".layui-layer-page").attr("times"));
                            });
                        }, 500);
                    });
                });
            });
        }*@
    }

    function initGridNotes() {

        var queryUrl = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/GetAnnotationNotes")';

        if (!is_combined_view) {
            queryUrl += '?recordingId=' + recording_id;
        } else {
            queryUrl += '?combined_recording_param=' + combined_recording_param;
        }

        $('#gridTableNotes').ysTable({
            url: queryUrl,
            sortName: 'time_start',
            sortOrder: 'asc',
            clickToSelect: true,
            pagination: true,
            toolbar: false,
            showColumns: false,
            showRefresh: false,
            showToggle: false,
            columns: [
                { field: 'time_start_label', title: 'Time Start' },
                { field: 'noter', title: 'Creator' },
                { field: 'note_html', title: 'Content' },
                //{ field: 'note_version', title: 'Note Version' },
                { field: 'created_at_text', title: 'Created At' }
            ],
            queryParams: function (params) {
                var pagination = $('#gridTableNotes').ysTable('getPagination', params);
                var queryString = $('#searchDivNotes').getWebControls(pagination);
                return queryString;
            }
        });
    }

    function initUtterancePopover() {
        $("#compare_result .utterance-bars").each(function () {
            var $this = $(this);
            var transcript_id = $this.data("transcript-id");
            var is_automated = $this.data("is-automated");
            var row_id = $this.closest(".row").attr("id");
            var content = '<div class="utterance-popover-item" onclick="popupEditUtterance(' + transcript_id + ',false)">Edit</div>' +
                '<div class="utterance-popover-item" onclick="popupEditUtterance(' + transcript_id + ',true)">Insert below</div>' +
                (is_automated == "0" ? '<div class="utterance-popover-item" onclick="popupDeleteUtterance(' + transcript_id + ')">Delete</div>' : '');

            $this.popover({
                title: "",
                html: true,
                container: 'body',
                placement: "bottom",
                trigger: 'focus',
                viewport: '#' + row_id,
                template: '<div class="popover" role="tooltip">' +
                    '<div class="popover-content utterance-popover-content"></div></div>',
                content: content
            });
        });
    }

    function popupDeleteUtterance(transcript_id) {
        ys.confirm("Are you sure that you want to delete it?", function () {
            $("#compare_result .utterance-bars").each(function () {
                var $this = $(this);

                if ($this.data("transcript-id") == transcript_id) {

                    var time_start = $this.data("timestart");
                    var transcript_recording_id = $this.data("recording-id");

                    var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SaveTranscript")';
                    var data = {
                        id: transcript_id,
                        recording_id: transcript_recording_id,
                        time_start: time_start,
                        is_deleted: 1
                    };

                    var deleted = false;

                    $this.css("visibility", "hidden");

                    $.post(url, data, function (obj) {
                        if (obj.Tag == 1) deleted = true;
                    }).always(function () {
                        $this.css("visibility", "visible");

                        if (deleted) {
                            $this.closest(".row").empty().remove();
                        }
                    });
                }
            });
        });
    }

    function popupEditUtterance(transcript_id, is_new) {
        $("#compare_result .utterance-bars").each(function () {
            var $that = $(this);

            if ($that.data("transcript-id") == transcript_id) {
                var row = $that.closest(".row");
                var spk = row.find(".speaker").text();
                var time = $that.data("timestart");
                var transcript_recording_id = $that.data("recording-id");
                var timestart_label = $that.data("timestart-label");
                var timestart_offset = $that.data("timestart-offset");

                var layer_html = $("#edit_utterance_template").html();
                var utter_div = $("<div/>");

                utter_div.html(row.find(".utterance-content").html());
                utter_div.find(".tooltiptext").remove();

                var utter = is_new ? "" : utter_div.text();
                var the_id = is_new ? "" : transcript_id;

                if (!is_new) {
                    if (row.find(".r6o-annotation").length > 0) {
                        ys.alertWarning("Please remove the annotations before updating the speech");
                        return;
                    }
                }

                ys.openDialogContent({ content: layer_html, width: '600px', height: 'auto' });

                setTimeout(function () {
                    $("#txtUtteranceTimestart").val(time).prop("disabled", !is_new);
                    $("#ddlUtteranceSpeaker").val(spk);
                    $("#txtUtteranceText").val(utter);
                    $("#hidTranscriptId").val(the_id);
                    $("#hidStartTimeOffsetSeconds").val(timestart_offset);

                    $("#btnUpdateUtterance").off("click").on("click", function () {
                        if (transcript_recording_id > 0) {
                            var $this = $(this);
                            var the_id = $("#hidTranscriptId").val();
                            var timestart_offset = $("#hidStartTimeOffsetSeconds").val();
                            var id = 0;
                            var speaker_text = $.trim($("#txtUtteranceText").val());
                            var speaker_label = $("#ddlUtteranceSpeaker").val();
                            var time_start = $.trim($("#txtUtteranceTimestart").val());
                            var spk_label = (speaker_label == "AGENT" ? "spk_0" : "spk_1");

                            if (speaker_text == "" || time_start == "") return;
                            if (the_id != "") id = parseInt(the_id);

                            // Find the first .speaker with the same speaker text
                            spk_label = $('#compare_result .speaker').filter(function () {
                                return this.innerText.indexOf(speaker_label) >= 0;
                            }).first().data('speaker-label') || spk_label;

                            $this.prop("disabled", true);

                            var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SaveTranscript")';
                            var data = {
                                id: id,
                                recording_id: transcript_recording_id,
                                time_start: time_start,
                                time_start_offset_seconds: timestart_offset,
                                speaker_label: spk_label,
                                speaker_text_en: speaker_text,
                                is_deleted: 0
                            };

                            var new_id = "";

                            $.post(url, data, function (obj) {
                                if (obj.Tag == 1) {
                                    if (is_new) new_id = obj.Data;
                                }
                            }).always(function () {
                                $this.prop("disabled", false);
                                layer.close($this.closest(".layui-layer-page").attr("times"));

                                if (!is_new) {
                                    row.find(".utterance-content").text(speaker_text);
                                    row.find(".speaker").text(speaker_label);
                                    row.find(".speaker").data('speaker-label', spk_label);
                                    row.find(".stripe").removeClass("agent customer");
                                    row.removeClass("agent_row customer_row");

                                    if (speaker_label == "AGENT") {
                                        row.addClass("agent_row");
                                        row.find(".stripe").addClass("agent");
                                    }
                                    else {
                                        row.addClass("customer_row");
                                        row.find(".stripe").addClass("customer");
                                    }
                                }

                                if (is_new && new_id != "") {
                                    var row_id = "transcript" + new_id;
                                    var html = $("#single_transcript_template").html();

                                    // Make it a clean string w/o extra chars
                                    html = html.replace(/[\r\n]/g, '');
                                    html = html.replace(/>[ ]+</g, '><');

                                    var $div = $("<div/>").html(html).find(".row").first();

                                    $div.attr('id', row_id);
                                    $div.insertAfter(row);

                                    if (speaker_label == "AGENT") {
                                        $div.addClass("agent_row");
                                        $div.find(".stripe").addClass("agent");
                                    }
                                    else {
                                        $div.addClass("customer_row");
                                        $div.find(".stripe").addClass("customer");
                                    }

                                    $div.find(".time").text(time_start);
                                    $div.find(".speaker").text(speaker_label);
                                    $div.find(".speaker").data('speaker-label', spk_label);

                                    var utter = $div.find(".utterance-content");

                                    utter.data("transcript-id", new_id);
                                    utter.data("timestart", time_start);
                                    utter.text(speaker_text);

                                    var utter_el = utter[0];
                                    var r = Recogito.init({
                                        content: utter_el,
                                        locale: 'auto',
                                        widgets: [{ widget: IntentWidget }],
                                        formatter: function (annotation) {
                                            var color_class = "";
                                            var intent_id = getAnnotationPurposeValue(annotation, 'intent_id');
                                            var intent = intent_list.find((i) => { return i.Id.toString() == intent_id });

                                            if (intent) color_class = intent.color_class;

                                            var is_automated = getAnnotationPurposeValue(annotation, 'is_automated');

                                            if (is_automated == "" || is_automated == "0") color_class += ' annotation-manual';

                                            return color_class;
                                        }
                                    });

                                    r.on('createAnnotation', function (annotation) {
                                        saveAnnotation(utter_el, annotation, null, 0);
                                    });

                                    r.on('updateAnnotation', function (annotation, previous) {
                                        var intent_id = getAnnotationPurposeValue(annotation, 'intent_id');
                                        var prev_id = getAnnotationPurposeValue(previous, 'intent_id');
                                        var note = getAnnotationPurposeValue(annotation, 'note');
                                        var prev_note = getAnnotationPurposeValue(previous, 'note');

                                        if (intent_id == prev_id && note == prev_note) return;

                                        saveAnnotation(utter_el, annotation, 0, 0);
                                    });

                                    r.on('deleteAnnotation', function (annotation) {
                                        saveAnnotation(utter_el, annotation, 0, 1);
                                    });

                                    var bar = $div.find(".utterance-bars");

                                    bar.data("transcript-id", new_id);
                                    bar.data("timestart", time_start);
                                    bar.data("timestart-label", timestart_label);
                                    bar.data("recording-id", transcript_recording_id);
                                    bar.data("timestart-offset", timestart_offset);

                                    bar.popover({
                                        title: "",
                                        html: true,
                                        container: 'body',
                                        placement: "bottom",
                                        trigger: 'focus',
                                        viewport: '#' + row_id,
                                        template: '<div class="popover" role="tooltip">' +
                                            '<div class="popover-content utterance-popover-content"></div></div>',
                                        content: function () {
                                            return '<div class="utterance-popover-item" onclick="popupEditUtterance(' + new_id + ',false)">Edit</div>' +
                                                '<div class="utterance-popover-item" onclick="popupEditUtterance(' + new_id + ',true)">Insert below</div>' +
                                                '<div class="utterance-popover-item" onclick="popupDeleteUtterance(' + new_id + ')">Delete</div>';
                                        }
                                    });
                                }
                            });
                        }
                    });

                    $("#btnCancelUtterance").off("click").on("click", function () {
                        layer.close($(this).closest(".layui-layer-page").attr("times"));
                    });
                }, 500);
            }
        });
    }
</script>

<script id="single_transcript_template" type="text/template">
    <div class="row transcript">
        <div class="stripe"></div>
        <div class="col-sm-1 time"></div>
        <div class="col-sm-1 speaker"></div>
        <div class="col-sm-9"><div class="utterance-content"></div></div>
        <div class="col-sm-1 text-left">
            <a tabindex="0" role="button" data-toggle="popover" class="utterance-bars"><i class="fa fa-edit"></i></a>
        </div>
    </div>
</script>

<script id="add_utterance_note_template" type="text/template">
    <div style="height:100%; padding:25px;">
        <div class="form-group">
            <input type="text" class="form-control" id="txtUtteranceNote" placeholder="Add a note...">
            <div id="utterance_note_msg" class="text-danger"></div>
        </div>
        <div class="form-group m-t-md text-right">
            <input id="btnCancelUtteranceNote" type="button" class="btn btn-default" value="Cancel" />&nbsp;&nbsp;
            <input id="btnAddUtteranceNote" type="button" class="btn btn-primary" value="Save" />
        </div>
        <div id="divUtteranceNote" style="display:none;">
            <h4>Notes</h4>
            <div id="lstUtteranceNote" style="max-height:250px; overflow:auto;"></div>
        </div>
    </div>
</script>

<script id="utterance_note_template" type="text/template">
    <div class="comment-item">
        <div class="comment-heading">
            <img class="img-circle comment-avatar" src="/image/portrait.png" />
            <span class="comment-author">{author}</span>&nbsp;-&nbsp;<span class="comment-time">{time}</span>
            <span class="comment-text">{txt}</span>
        </div>
        <div class="comment-body">{html}</div>
    </div>
</script>

<script id="anno_template" type="text/template">
    <select></select>
    <input class="form-control" style="margin-top:20px;" placeholder="Add a note..." />
</script>

<script id="edit_utterance_template" type="text/template">
    <div style="padding:30px;">
        <div class="form-group">
            <label for="txtUtteranceTimestart">Time</label>
            <input type="text" class="form-control" id="txtUtteranceTimestart" />
        </div>
        <div class="form-group">
            <label for="ddlUtteranceSpeaker">Speaker</label>
            <select id="ddlUtteranceSpeaker" class="form-control">
                <option value="AGENT">AGENT</option>
                <option value="CUSTOMER">CUSTOMER</option>
            </select>
        </div>
        <div class="form-group">
            <label for="txtUtteranceText">Transcript</label>
            <textarea type="text" class="form-control" id="txtUtteranceText" rows="5" style="resize:vertical; width:100%"></textarea>
        </div>
        <div class="m-t-md text-right">
            <input type="hidden" id="hidTranscriptId" />
            <input type="hidden" id="hidStartTimeOffsetSeconds" />
            <input id="btnCancelUtterance" type="button" class="btn btn-default" value="Cancel" />&nbsp;&nbsp;
            <input id="btnUpdateUtterance" type="button" class="btn btn-primary" value="Save" />
        </div>
    </div>
</script>

<script id="edit_recordingintent_template" type="text/template">
    <div style="padding:30px;">
        <div class="form-group">
            <label id="lblRecordingIntent">Intent</label>
        </div>
        <div class="form-group">
            <label for="ddlRecordingIntentFinding">Finding</label>
            <select id="ddlRecordingIntentFinding" class="form-control">
                <option value="1">Found</option>
                <option value="0">No found</option>
            </select>
        </div>
        <div class="form-group">
            <label for="txtRecordingIntentScore">Score</label>
            <input type="text" class="form-control" id="txtRecordingIntentScore" />
        </div>
        <div class="m-t-md text-right">
            <input id="btnCancelRecordingIntent" type="button" class="btn btn-default" value="Cancel" />&nbsp;&nbsp;
            <input id="btnUpdateRecordingIntent" type="button" class="btn btn-primary" value="Save" />
        </div>
    </div>
</script>

<script>
    var sample_anno = {
        '@@context': 'http://www.w3.org/ns/anno.jsonld',
        'id': 'https://www.example.com/recogito-js-example/foo',
        'type': 'Annotation',
        'body': [
            {
                'type': 'TextualBody',
                'value': '2',
                'purpose': 'intent_id'
            }
        ],
        'target': {
            'selector': [
                {
                    'type': 'TextQuoteSelector',
                    'exact': 'tele'
                }, {
                    'type': 'TextPositionSelector',
                    'start': 38,
                    'end': 57
                }
            ]
        }
    };

    var IntentWidget = function (args) {
        var currentIntentBody = args.annotation ?
            args.annotation.bodies.find(function (b) {
                return b.purpose == 'intent_id';
            }) : null;

        var currentNoteBody = args.annotation ?
            args.annotation.bodies.find(function (b) {
                return b.purpose == 'note';
            }) : null;

        var intent_id = currentIntentBody ? currentIntentBody.value : "";
        var note = currentNoteBody ? currentNoteBody.value : "";

        var formatOption = function (option) {
            if (!option.id) return option.text;

            var intent = intent_list.find((i) => { return i.Id.toString() == option.id });

            if (intent) {
                var $option = $('<div><span class="option-legend"></span><span class="option-text"></span></div>');

                $option.find(".option-legend").addClass(intent.color_class);
                $option.find(".option-text").text(option.text);

                return $option;
            }

            return option.text;
        };

        var selectorChanged = function (evt) {
            addIntentBody(evt.target.value);
        }

        var inputChanged = function (evt) {
            addNoteBody(evt.target.value);
        }

        var addIntentBody = function (intent_id) {
            if (intent_id == "") return;

            if (currentIntentBody) {
                args.onUpdateBody(currentIntentBody, {
                    type: 'TextualBody',
                    purpose: 'intent_id',
                    value: intent_id
                });
            } else {
                args.onAppendBody({
                    type: 'TextualBody',
                    purpose: 'intent_id',
                    value: intent_id
                });

                // Not know why the 2nd onAppendBody overwrites the 1st unless it runs a bit later
                setTimeout(function () {
                    args.onAppendBody({
                        type: 'TextualBody',
                        purpose: 'is_automated',
                        value: '0'
                    });
                }, 0);
            }
        }

        var addNoteBody = function (note) {
            if (currentNoteBody) {
                args.onUpdateBody(currentNoteBody, {
                    type: 'TextualBody',
                    purpose: 'note',
                    value: note
                });
            } else {
                args.onAppendBody({
                    type: 'TextualBody',
                    purpose: 'note',
                    value: note
                });
            }
        }

        var $div = $("<div>").html($("#anno_template").html());
        var $selector = $div.find("select");
        var $input = $div.find("input");

        intent_list.forEach(function (intent) {
            var option = new Option(intent.name, intent.Id.toString(), false, false);

            $selector.append(option);
        });

        $selector.val(intent_id).select2({
            placeholder: "Select a Tag",
            minimumResultsForSearch: -1,
            templateResult: formatOption,
            templateSelection: formatOption
        }).on('change', selectorChanged);

        $input.val(note).on('change', inputChanged);

        return $div[0];
    }

    var intent_list = [];

    function initAnnotations(obj) {
        return new Promise((resolve) => {
            var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/GetIntentList")';

            $.get(url, function (result) {
                if (result.Tag == 1) intent_list = result.Data;
            }).always(function () {
                $("#compare_result .utterance-content").each(function () {
                    var that = this;
                    var r = Recogito.init({
                        content: this,
                        locale: 'auto',
                        widgets: [{ widget: IntentWidget }],
                        formatter: function (annotation) {
                            var color_class = "";
                            var intent_id = getAnnotationPurposeValue(annotation, 'intent_id');
                            var intent = intent_list.find((i) => { return i.Id.toString() == intent_id });

                            if (intent) color_class = intent.color_class;

                            var is_automated = getAnnotationPurposeValue(annotation, 'is_automated');

                            if (is_automated == "" || is_automated == "0") color_class += ' annotation-manual';

                            return color_class;
                        }
                    });

                    r.on('createAnnotation', function (annotation) {
                        saveAnnotation(that, annotation, null, 0);
                    });

                    r.on('updateAnnotation', function (annotation, previous) {
                        var intent_id = getAnnotationPurposeValue(annotation, 'intent_id');
                        var prev_id = getAnnotationPurposeValue(previous, 'intent_id');
                        var note = getAnnotationPurposeValue(annotation, 'note');
                        var prev_note = getAnnotationPurposeValue(previous, 'note');

                        if (intent_id == prev_id && note == prev_note) return;

                        saveAnnotation(that, annotation, 0, 0);
                    });

                    r.on('deleteAnnotation', function (annotation) {
                        saveAnnotation(that, annotation, 0, 1);
                    });

                    var annotations = obj.Data.annotations.filter((a) => { return a.transcript_id == $(this).data('transcript-id'); });

                    //if ($(this).data('timestart') == '0:04:48') {
                    //    alert($(this).data('transcript-id'));
                    //}

                    $.each(annotations, function (index, item) {
                        var anno = {
                            '@@context': 'http://www.w3.org/ns/anno.jsonld',
                            'id': item.uuid,
                            'type': 'Annotation',
                            'body': [
                                {
                                    'type': 'TextualBody',
                                    'value': item.intent_id.toString(),
                                    'purpose': 'intent_id'
                                },
                                {
                                    'type': 'TextualBody',
                                    'value': item.is_automated.toString(),
                                    'purpose': 'is_automated'
                                },
                                {
                                    'type': 'TextualBody',
                                    'value': item.note_html || "",
                                    'purpose': 'note'
                                }
                            ],
                            'target': {
                                'selector': [
                                    {
                                        'type': 'TextQuoteSelector',
                                        'exact': item.annotation_text || ""
                                    },
                                    {
                                        'type': 'TextPositionSelector',
                                        'start': item.position_start,
                                        'end': item.position_start + item.annotation_text.length
                                    }
                                ]
                            }
                        };

                        r.addAnnotation(anno);
                    });
                });

                resolve(true);
            });
        });
    }

    function getAnnotationPurposeValue(annotation, purpose) {
        var value = "";
        var body = annotation.body.find((b) => { return b.purpose == purpose });

        if (body) value = body.value.toString();

        return value;
    }

    function saveAnnotation(element, annotation, anno_id, is_deleted) {
        if (recording_id > 0) {
            var intent_id = getAnnotationPurposeValue(annotation, 'intent_id');
            var note = $.trim(getAnnotationPurposeValue(annotation, 'note'));
            var anno_text = '';
            var pos_start = -1;
            var txt_selector = annotation.target.selector.find((s) => { return s.type == 'TextQuoteSelector' });
            var pos_selector = annotation.target.selector.find((s) => { return s.type == 'TextPositionSelector' });
            var time_start = $(element).data("timestart") || "";
            var transcript_id = $(element).data("transcript-id") || "0";
            var transcript_recording_id = $(element).data("recording-id") || "0";

            if (txt_selector) anno_text = txt_selector.exact;
            if (pos_selector) pos_start = pos_selector.start;
            if (intent_id == '' || anno_text == '' || time_start == "" || pos_start < 0) return;

            var url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SaveAnnotation")';

            // Annotations are identified by time_start and uuid.
            // For now, if anno_id is null, it means a new one.
            var data = {
                id: anno_id,
                uuid: annotation.id,
                intent_id: parseInt(intent_id),
                recording_id: transcript_recording_id,
                time_start: time_start,
                annotation_text: anno_text,
                position_start: pos_start,
                is_deleted: is_deleted,
                transcript_id: transcript_id,
                note_html: note
            };

            $.post(url, data, function (obj) {
                if (obj.Tag == 1) {
                    getUtteranceNotes();
                    refresh_notes_table = true;
                }
            }).always(function () {
            });

            @*if (is_deleted == 0 && note != "") {
                url = '@Url.Content("~/BusinessManage/CallRecordingAnalysis/SaveUtteranceNote")';
                data = {
                    recording_id: recording_id,
                    time_start: time_start,
                    note_html: note
                };

                $.post(url, data, function (obj) {
                    if (obj.Tag == 1) {
                        getUtteranceNotes();
                        refresh_notes_table = true;
                    }
                }).always(function () {
                    var noteBody = annotation.body.find((b) => { return b.purpose == 'note' });

                    if (noteBody) noteBody.value = "";
                });
            }*@
        }
    }
</script>
